package com.zqxq.lottery.api.alipay.util;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.zqxq.lottery.api.alipay.config.AlipayConfig;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/* *
 *类名：AlipayFunction
 *功能：支付宝接口公用函数类
 *详细：该类是请求、通知返回两个文件所调用的公用函数核心处理文件，不需要修改
 *版本：3.3
 *日期：2012-08-14
 *说明：
 *以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
 */

public class AlipayCore {

    private static String payServerUrl = "https://openapi.alipay.com/gateway.do";
    private static String app_id = "";
    private static String private_key = "";
    private static String alipay_public_key = "";

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new HashMap<String, String>();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    /**
     * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
     *
     * @param sWord 要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(AlipayConfig.log_path + "alipay_log_" + System.currentTimeMillis() + ".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    /**
//     * 生成文件摘要
//     * @param strFilePath 文件路径
//     * @param file_digest_type 摘要算法
//     * @return 文件摘要结果
//     */
//    public static String getAbstract(String strFilePath, String file_digest_type) throws IOException {
//        PartSource file = new FilePartSource(new File(strFilePath));
//    	if(file_digest_type.equals("MD5")){
//    		return DigestUtils.md5Hex(file.createInputStream());
//    	}
//    	else if(file_digest_type.equals("SHA")) {
//    		return DigestUtils.sha256Hex(file.createInputStream());
//    	}
//    	else {
//    		return "";
//    	}
//    }
//
//
//
//
//    /**
//     *
//     * @方法名称:alipayRefundRequest
//     * @内容摘要: ＜支付宝退款请求＞
//     * @param out_trade_no 订单支付时传入的商户订单号,不能和 trade_no同时为空。
//     * @param trade_no 支付宝交易号，和商户订单号不能同时为空
//     * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
//     * @return
//     */
//    public String refund(String out_trade_no,String trade_no,double refund_amount){
//
//    	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
//    	AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//    	request.setBizContent("{" +
//    	"    \"out_trade_no\":\""+out_trade_no+"\"," +
//    	//"    \"trade_no\":\"2014112611001004680073956707\"," +
//    	"    \"refund_amount\":"+refund_amount+"," +
//    	"    \"refund_reason\":\"正常退款\"," +
//    	//"    \"out_request_no\":\"HZ01RF001\"," +
//    	//"    \"operator_id\":\"OP001\"," +
//    	//"    \"store_id\":\"NJ_S_001\"," +
//    	"    \"terminal_id\":\"NJ_T_001\"" +
//    	"  }");
//
//    	AlipayTradeRefundResponse response;
//		try {
//			response = alipayClient.execute (request);
//			if(response.isSuccess()){
//		    	System.out.println("调用成功");
//		    	} else {
//		    	System.out.println("调用失败");
//		    	}
//
//		} catch (AlipayApiException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//    	return "";
//    }

    /**
     * 创建支付宝支付交易接口
     */
    public static void createAlipay(String out_trade_no,Double total_amount,String subject,String notify_url) {
        AlipayClient alipayClient = new DefaultAlipayClient(payServerUrl, app_id, private_key, "json", "utf-8", alipay_public_key, "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl(notify_url); //设置回调地址
        /*
        * out_trade_no:商户订单号
        * seller_id:卖家支付宝用户ID
        * total_amount:订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        * discountable_amount:可打折金额. 参与优惠计算的金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        * subject:订单标题
        * body:对交易或商品的描述
        * buyer_id:买家的支付宝唯一用户号（2088开头的16位纯数字）,和buyer_logon_id不能同时为空
        * goods_detail:商品描述
        * extend_params:业务扩展参数
        * timeout_express:该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m
        * business_params:商户传入业务信息，具体值要和支付宝约定，应用于安全，营销等参数直传场景，格式为json格式
        * */
        request.setBizContent("{" +
                "\"out_trade_no\":\""+out_trade_no+"\"," +
                /*"\"seller_id\":\"2088102146225135\"," +*/
                "\"total_amount\":"+total_amount+"," +
                /*"\"discountable_amount\":8.88," +*/
                "\"subject\":\""+subject+"\"," +
                /*"\"body\":\"Iphone616G\"," +*/
                "\"buyer_id\":\"2088102146225135\"," +
                "\"goods_detail\":[{" +
                "\"goods_id\":\"apple-01\"," +
                "\"goods_name\":\"ipad\"," +
                "\"quantity\":1," +
                "\"price\":2000," +
                "\"goods_category\":\"34543238\"," +
                "\"body\":\"特价手机\"," +
                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                "}]," +
                "\"operator_id\":\"Yx_001\"," +
                "\"store_id\":\"NJ_001\"," +
                "\"terminal_id\":\"NJ_T_001\"," +
                "\"extend_params\":{" +
                "\"sys_service_provider_id\":\"2088511833207846\"" +
                "}," +
                "\"timeout_express\":\"90m\"," +
                "\"business_params\":\"{\\\"data\\\":\\\"123\\\"}\"" +
                "}");
        AlipayTradeCreateResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
